#!/bin/bash
#
# Description: Create slide thumbnail, including label
# 
# The MIT License (MIT)
# Copyright (c) 2014-2016, Bas G.L. Nelissen, UMC Utrecht, the Netherlands.
# 
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
# 
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# 

# Variables
SCRIPTNAME=$(basename $0)
DESCRIPTIONSHORT="Create slide thumbnail, including label"
DEPENDENCIES=("convert" "perl")
SUPPORTED_FORMATS=("Generic-TIFF" "Aperio" "Hamamatsu" "iScan" "iScanHT" "Leica")
DEFAULT_OUTPUT_SUFFIX=".thumb"
DEFAULT_OUTPUT_EXTENSION="png"
DEFAULT_OUTPUT_DIRECTORY="." # Relative to input file
DEFAULT_RESIZE="1024x1024"
# sort arrays
DEPENDENCIES=( $( for el in "${DEPENDENCIES[@]}"; do echo "$el"; done | sort) )
SUPPORTED_FORMATS=( $( for el in "${SUPPORTED_FORMATS[@]}"; do echo "$el"; done | sort) )

# Errors go to stderr
err() {
  echo "${SCRIPTNAME} ERROR: $@" >&2
}

# usage message
usage() {
cat <<- EOF
$SCRIPTNAME --help for more information.
EOF
}

# version info
version() {
cat << EOF
slideToolkit 0.1 beta
($SCRIPTNAME is part of the slideToolkit)

The MIT License (MIT) <http://opensource.org/licenses/MIT>
Copyright (c) 2014-2016, Bas G.L. Nelissen, UMC Utrecht, the Netherlands.

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

There is NO WARRANTY, to the extent permitted by law.

Written by Bas G.L. Nelissen | https://github.com/bglnelissen.
EOF
}


# help message
helpMessage() {
cat <<- EOF
${SCRIPTNAME}: ${DESCRIPTIONSHORT}

usage:
  $SCRIPTNAME [options] -f <filename>

options:
  -f, --file <filename>       extract the thumbnail from this virtual slide

  [-l, --layer] <integer>     force specific layer by layer id
  [--suffix] <text>           suffix to filename ["$DEFAULT_OUTPUT_SUFFIX"]
  [--extension] <text>        thumbnail output extension ["$DEFAULT_OUTPUT_EXTENSION"]
  [--output-dir] <path>       path to output directory
  [--resize] <widthxheight>   maximum output dimentions ["$DEFAULT_RESIZE"]
  [--ignore-dependencies]     ignores all dependencies, but gives warning
  
  --help                      display this help
  --version                   display version and license information


examples:
  $SCRIPTNAME "file.svs"
  $SCRIPTNAME  --layer=5 --suffix=".suffix" --extension="jpg" "file.tif"

print a job list:
  find "\$(pwd)" -iname "*.TIF" -exec "$(command -v "$SCRIPTNAME")" -f "{}" \;

print a job list for 'qsub':
  for i in \$(find ./ -iname "*tif"); do
    j="\$(echo "\$(cd "\$(dirname "\$i")"; pwd)"/"\$(basename "\$i")")"; \\
    echo "qsub" -pe threaded 1 -q veryshort \\
    "$(command -v "$SCRIPTNAME")" --file="\${j}"
  done

dependencies: ${DEPENDENCIES[@]}
supported formats: ${SUPPORTED_FORMATS[@]}

A virtual slide is usually variant of a multilayered/pyramid TIFF file.
Different vendors store an overview of each slide in one (or more) of
these layers. This script extracts the correct layers and resizes,
rotates and concatenates when necessary. By default the thumbnail is
created in the same folder as the original file, a specific output
directory can be set with --output-dir (path can be a relative path or
absolute path, if the location does not exist it will be created). Pipe
the 'job list' output in 'parallel' for parallel processing.

The slideToolkit and all its tools are released under the terms of the MIT license.
The slideToolkit (C) 2014-2016, Bas G.L. Nelissen, UMC Utrecht, the Netherlands.
Report issues at https://github.com/bglnelissen/slideToolkit/issues.

EOF
}

# Menu
# Empty variables
FILE=""
LAYER=""
OUTPUT_SUFFIX=""
OUTPUT_EXTENSION=""
OUTPUT_DIRECTORY=""
# illegal option
illegalOption() {
cat <<- EOF
$SCRIPTNAME: illegal option $1
$(usage)
EOF
exit 1
}
# loop through options
while :
do
  case $1 in
    --help | -\?)
      helpMessage
      exit 0 ;;
    --version )
      version
      exit 0 ;;
    --h)
      usage
      exit 0 ;;
    -f | --file)
      FILE=$2
      shift 2 ;;
    -l | --layer)
      LAYER=$2
      shift 2 ;;
    --layer=*)
      LAYER=${1#*=}
      shift ;;
    --file=*)
      FILE=${1#*=}
      shift ;;
    --suffix)
      OUTPUT_SUFFIX=$2
      shift 2;;
    --suffix=*)
      OUTPUT_SUFFIX=${1#*=}
      shift ;;
    --resize=*)
      RESIZE=${1#*=}
      shift ;;
    --resize)
      RESIZE=$2
      shift 2 ;;
    --extension)
      OUTPUT_EXTENSION=$2
      shift 2;;
    --extension=*)
      OUTPUT_EXTENSION=${1#*=}
      shift ;;
    --output-dir)
      OUTPUT_DIRECTORY=$2
      shift 2;;
    --output-dir=*)
      OUTPUT_DIRECTORY=${1#*=}
      shift ;;
     --ignore-dependencies)
      IGNOREDEPENDENCIES=TRUE
      shift ;;
    --) # End of all options
      shift
      break ;;
    -*)
      illegalOption "$1"
      shift ;;
    *)  # no more options. Stop while loop
      break ;;
  esac
done
# DEFAULTS
# set FILE default
if [ "$FILE" != "" ]; then
  FILE="$FILE"
else
  FILE="$1"
fi

# set OUTPUT_SUFFIX default
if [ "$OUTPUT_SUFFIX" != "" ]; then
  OUTPUT_SUFFIX="$OUTPUT_SUFFIX"
else
  OUTPUT_SUFFIX="$DEFAULT_OUTPUT_SUFFIX"
fi
# set OUTPUT_EXTENSION default
if [ "$OUTPUT_EXTENSION" != "" ]; then
  OUTPUT_EXTENSION="$OUTPUT_EXTENSION"
else
  OUTPUT_EXTENSION="$DEFAULT_OUTPUT_EXTENSION"
fi
# set OUTPUT_DIRECTORY default
if [ "$OUTPUT_DIRECTORY" != "" ]; then
  OUTPUT_DIRECTORY="$OUTPUT_DIRECTORY"
else
  OUTPUT_DIRECTORY="$DEFAULT_OUTPUT_DIRECTORY"
fi
# set RESIZE default
if [ "$RESIZE" != "" ]; then
  RESIZE="$RESIZE"
else
  RESIZE="$DEFAULT_RESIZE"
fi
# set IGNOREDEPENDENCIES  (this if statement does nothing, as it is set to set in Menu)
if [[ "$IGNOREDEPENDENCIES" =~ (true|TRUE|YES|yes) ]] ; then
  IGNOREDEPENDENCIES=true
else
  IGNOREDEPENDENCIES=false
fi

# requirements
checkRequirements() {
  if ! [[ -f "$FILE" ]] ; then
    err "No such file: $FILE"
    usage
    exit 1
  fi
}

# Dependencies
checkDependencies(){
  DEPS=""
  DEPS_FAIL="0"
  for DEP in ${DEPENDENCIES[@]}; do
    if [[ 0 != "$(command -v "$DEP" >/dev/null ;echo "$?")" ]]; then
       err "Missing dependency: $DEP"
       DEPS_FAIL=$(($DEPS_FAIL + 1))
    fi
  done
  if [[ "$DEPS_FAIL" > 0 ]]; then
    # only warning when --ignore-dependencies is set.
    if [[ "$IGNOREDEPENDENCIES" == "true" ]]; then
      err "Ignoring missing dependencies (${DEPS_FAIL}), continue..."
    else
      err "Fix missing dependencies (${DEPS_FAIL}), exit."
      usage
      exit 1
    fi
  fi
}
# get thumb for each scanner type
getThumb(){
  # get thumb by layer id
  LAYER="$LAYER"
  convert "$FILEFULL[$LAYER]" -resize "$RESIZE" "$OUTPUTFILENAME"
}
getThumbiScanHT(){
  LAYER=0
  convert "$FILEFULL[$LAYER]" -resize "$RESIZE" "$OUTPUTFILENAME"
}
getThumbAperio(){
  # the last 2 layers contain thumb and the tissue (couning starts at 0)
  NR_LAYERS=`identify "$FILE" | wc -l`
  N_LABEL="$(($NR_LAYERS - 2))"
  N_TISSUE="$(($NR_LAYERS - 1))"
  # get label, get tissue, rotate one and resize both, then append and do a final resize
  convert "$FILEFULL[$N_LABEL]" -resize 1024x \( "$FILEFULL[$N_TISSUE]" -rotate 90 -resize 1024x \)-append -resize "$RESIZE" "$OUTPUTFILENAME"
}
getThumbLeica(){
  LAYER=1 # determined from example file (http://openslide.cs.cmu.edu/download/openslide-testdata/)
  convert "$FILEFULL"[$LAYER] -rotate 180 -resize "$RESIZE" "$OUTPUTFILENAME"
}
getThumbHamamatsu(){
  LAYER=10 # determined from example file (http://openslide.cs.cmu.edu/download/openslide-testdata/)
  convert "$FILEFULL"[$LAYER] -rotate 90 -resize "$RESIZE" "$OUTPUTFILENAME"
}
getThumbiScan(){
  LAYER=0 # determined from example file (http://openslide.cs.cmu.edu/download/openslide-testdata/)
  convert "$FILEFULL"[$LAYER] -resize "$RESIZE" "$OUTPUTFILENAME"
}
programOutput(){
  # set variables
  FILE="$FILE"
  # path variables
  FILEFULL="$(echo "$(cd "$(dirname "$FILE")"; pwd)"/"$(basename "$FILE")")" # full path $FULL
  DIRFULL="$(echo "$(cd "$(dirname "$FILE")"; pwd)")"
  BASENAME="$(basename "$FILEFULL")"    # basename
  DIRNAME="$(dirname "$FILE")"          # dirname
  EXTENSION="${BASENAME##*.}"           # extension
  FILEPATH="${FILEFULL%.*}"             # full path, no extension
  FILENAME="${BASENAME%.*}"             # filename, no extension"
  # Check if path to OUTPUT_DIRECTORY is absolute or relative
  if [[ "$OUTPUT_DIRECTORY" = /* ]]
  then
   # Absolute path is found, use it
   OUTPUT_DIRECTORY_PATH="$OUTPUT_DIRECTORY"
  else
   # Relative path
   OUTPUT_DIRECTORY_PATH="${DIRFULL}/${OUTPUT_DIRECTORY}"
  fi
  # Create the path if it does not exist
  mkdir -p "$OUTPUT_DIRECTORY_PATH"
  # The final path for the output file is:
  OUTPUTFILENAME="${OUTPUT_DIRECTORY_PATH}/${FILENAME}${OUTPUT_SUFFIX}.${OUTPUT_EXTENSION}"
  
  # check metadata for scanner data
  if [ "$LAYER" != "" ]; then
    getThumb # layer is set, do it the easy way
  elif [[ "0" < "$(tiffinfo  "$FILEFULL" 2>&1 | strings | grep -i "iScanHT" | wc -l | awk '{print $1}' )" ]]; then
    getThumbiScanHT # iScanHT found
  elif [[ "0" < "$(tiffinfo  "$FILEFULL" 2>&1 | strings | grep -i "Aperio" | wc -l | awk '{print $1}')" ]]; then
    getThumbAperio  # Aperio found
  elif [[ "0" < "$(tiffinfo  "$FILEFULL" 2>&1 | strings | grep -i "Leica" | wc -l | awk '{print $1}')" ]]; then
    getThumbLeica  # Leica found
  elif [[ "0" < "$(tiffinfo  "$FILEFULL" 2>&1 | strings | grep -i "Hamamatsu" | wc -l | awk '{print $1}')" ]]; then
    getThumbHamamatsu  # Hamamatsu found
  elif [[ "0" < "$(tiffinfo  "$FILEFULL" 2>&1 | strings | grep -i "iScan" | wc -l | awk '{print $1}')" ]]; then
    getThumbiScan  # iScan found
  else
    err "Unknown virtual slide format: $FILE"
    err "You probably want to set --layer manually."
    err "Run slideInfo for layer information."
    usage
    exit 1
  fi
}

# all check?
checkRequirements
checkDependencies

# lets go!
programOutput
